const cmd = require('child_process')
const ora = require('ora')
const fs = require('fs')
const path = require('path')
const moment = require('moment')
const utils = require('./utils')
let loading = ora()

// 临时存放 archive 产物的路径，后续会删除
const archivePath = './package-ios-temp-archive/temp.xcarchive'
// config.json 转化的 json
var configInfo = null
// 打包命令中需要的参数
var project = null

// child_process.exec 所需的参数，避免 maxBuffer 不足而导致错误
const execOption = {
        encoding: 'utf8',
        timeout: 0,
        maxBuffer: 1000 * 1024 * 1024, // 默认 200 * 1024
        killSignal: 'SIGTERM'
    }

/*
 * 开始打包
 * 
 * - clean
 * - archive
 * - export
 */
async function start() {
    try {
        utils.exportPlistExist()
        utils.configJsonExist()
        
        let startTime = new Date().getTime();
        await readConfigFile()
        await clean()
        await archive()
        await exportFunc()
        await openWebBrowser()
        let endTime = new Date().getTime()
        console.log(`总耗时：[${(endTime-startTime)/1000} sec]`)
    } catch (error) {
        console.log(error)
    }
}

// 读取 config.json 文件
function readConfigFile() {
    return new Promise((resolve, reject) => {
        fs.readFile(utils.configJsonPath, (err, data) => {
            if (err) {
                return reject(err)
            }
            configInfo = JSON.parse(data.toString())
            // 判断工程是否使用的是 workspace
            project = configInfo.project.includes('.xcworkspace') ? 'workspace' : 'project'
            resolve()
        })
    })
}

function clean() {
    return new Promise((resolve, reject) => {
        loading.text = 'cleaning...'
        loading.start()
        const clean_cmd = `xcodebuild clean -${project} ${configInfo.project} -scheme ${configInfo.scheme} -configuration ${configInfo.configuration}`
        cmd.exec(clean_cmd, execOption, (err, stdout) => {
            loading.stop()
            if (err) {
                return reject(err)
            }
            utils.printSuccessLog('clean succeeded')
            resolve()
        })
    })
}

function archive() {
    return new Promise((resolve, reject) => {
        loading.text = 'archiving...'
        loading.start()
        const archive_cmd = `xcodebuild archive -${project} ${configInfo.project} -scheme ${configInfo.scheme} -configuration ${configInfo.configuration} -archivePath ${archivePath}`
        cmd.exec(archive_cmd, execOption, (err, stdout) => {
            loading.stop()
            if (err) {
                return reject(err)
            }
            utils.printSuccessLog('archive succeeded')
            resolve()
        })
    })
}
/*
 * 导出 archive 包
 * 
 * - 定义导出路径
 * - 结束后删除临时存储的 archive 产物 
 */
function exportFunc() {
    // archivepath 的上一级需要一起删除
    let archiveRoot = path.resolve(archivePath, '../')
    // 在既定的导出路径后面添加一个时间文件夹区分 文件夹中有空格需要将整体用 "" 包裹起来
    let d = new Date()
    
    let cur_date = moment().format('YYYY-MM-DD HH:mm:ss')
    let exportPath = path.resolve(configInfo.exportPath, `"${configInfo.scheme} ${cur_date}"`)
    return new Promise((resolve, reject) => {
        loading.text = 'exporting...'
        loading.start()
        const export_cmd = `xcodebuild -exportArchive -exportOptionsPlist ${utils.exportPlistPath} -archivePath ${archivePath} -exportPath ${exportPath} -allowProvisioningUpdates`
        cmd.exec(export_cmd, execOption, (err, stdout) => {
            loading.stop()
             if (err) {
                cmd.execSync(`rm -r ${archiveRoot}`)
                return reject(err)
             }
             utils.printSuccessLog('export succeeded')
             cmd.execSync(`rm -r ${archiveRoot}`)
             utils.printSuccessLog(`delete ${archiveRoot} succeeded`)
             resolve()
         })
    })
}

/*
 * 打开包管理平台
 */
function openWebBrowser() {
    let open_cmd = 'open http://package.weimobapp.com/application/page'
    return new Promise((resolve, reject) => {
        cmd.exec(open_cmd, (err, stdout) => {
            if (err) {
                return reject(err)
            }
            utils.printSuccessLog(open_cmd)
            resolve()
        })
    })
}

module.exports = start;